package com.sunsun_china.www.aq.base;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 *
 */
public class HttpUtils {

	private static int sendNum = 0;

	/**
	 * 使用Get方式获取数据
	 *
	 * @param url     URL包括参数，http://HOST/XX?XX=XX&XXX=XXX
	 * @param charset
	 * @return
	 */
	public static String sendGet(String url, String charset) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			//MyLogger.error("发送GET请求出现异常！" + e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * POST请求，字符串形式数据
	 *
	 * @param url     请求地址
	 * @param param   请求数据
	 * @param charset 编码方式
	 */
	public static String sendPostUrl(String url, String param, String charset, String contentType) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = (URLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", contentType);
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			//conn.setRequestMethod("POST");
			//conn.setUseCaches(false);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			url = e.getMessage();
			//MyLogger.error("发送 POST 请求出现异常！" + e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				//MyLogger.error("send post appears io exception" ,ex);
			}
		}

		sendNum++;
		//MyLogger.info("HTTP 第" + sendNum  + "次请求完成... ");
		return result;
	}

	/**
	 * POST请求，Map形式数据
	 *
	 * @param url     请求地址
	 * @param param   请求数据
	 * @param charset 编码方式
	 */
	public static String sendPost(String url, Map<String, String> param,
								  String charset) {

		StringBuffer buffer = new StringBuffer();
		if (param != null && !param.isEmpty()) {
			for (Map.Entry<String, String> entry : param.entrySet()) {
				try {
					buffer.append(entry.getKey())
							.append("=")
							.append(URLEncoder.encode(entry.getValue(), charset))
							.append("&");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				/*buffer.append(entry.getKey()).append("=")
						.append(entry.getValue()).append("&");*/
			}
		}
		buffer.deleteCharAt(buffer.length() - 1);
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			//conn.setRequestProperty("Accept-Charset", charset);
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(buffer);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			//MyLogger.error("发送 POST 请求出现异常！" + e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url      发送请求的 URL
	 * @param PostData 请求参数，请求参数应该是 二进制字节流 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static byte[] Post(String url, byte[] PostData) {
		PrintWriter out = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			//conn.setRequestProperty("Accept-Charset", charset);
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			OutputStream outStream = conn.getOutputStream();
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			outStream.write(PostData);
			outStream.flush();
			outStream.close();
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应

			int len = -1;
			byte[] bs = null;
			int contentLength = conn.getContentLength();
			if (contentLength != -1)
				bs = new byte[contentLength];
			else
				bs = new byte[1024];
			while ((len = conn.getInputStream().read(bs)) != -1) {
				bos.write(bs, 0, len);
			}
			byte[] b = bos.toByteArray();
			return b;
		} catch (Exception e) {
			//MyLogger.error("发送 POST 请求出现异常！" + e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return new byte[0];
	}

	public static void main(String[] args) throws IOException {
		String res = HttpUtils.sendGet("http://app.kookong.com/m/brands?app=android&deviceType=2&version=101&sdk=18", "utf-8");
		System.out.println("res = [" + res + "]");

		Map<String, String> params = new HashMap<String, String>();
		params.put("app", "android");
		params.put("deviceType", "2");
		params.put("version", "101");
		params.put("sdk", "18");
		String res2 = HttpUtils.sendPost("http://app.kookong.com/m/brands", params, "iso88591-1");
		System.out.println("res2 = [" + res2 + "]");
	}

	public static int getSendNum() {
		return sendNum;
	}

	public static void setSendNum(int sendNum) {
		HttpUtils.sendNum = sendNum;
	}
}
